<template>
  <div class="cart-container">
    <!-- 顶部导航 -->
    <van-nav-bar title="购物车" left-arrow />

    <!-- 购物车列表 -->
    <div class="cart-list">
      <!-- 购物车商品项 -->
      <div class="cart-item" v-for="(item, index) in cartItems" :key="index">
        <!-- 选择框 -->
        <van-checkbox v-model="item.checked" @change="calculateTotal" />

        <!-- 商品图片 -->
        <img :src="item.img1" :alt="item.proname" class="item-image">

        <!-- 商品信息 -->
        <div class="item-info">
          <h3 class="item-name">{{ item.proname.slice(0, 10) }}</h3>
          <p class="item-price">¥{{ item.originprice.toFixed(2) }}</p>

          <!-- 数量调整 -->
          <van-stepper v-model="item.num" :min="1" @change="calculateTotal" />
        </div>

        <!-- 删除按钮 -->
        <van-icon name="delete" color="#f4333c" @click="deleteItem(index)" />
      </div>

      <!-- 空购物车状态 -->
      <van-empty v-if="showEmpty" image="shopping-cart" description="购物车是空的">
        <van-button type="primary">去购物</van-button>
      </van-empty>
    </div>

    <!-- 底部结算栏 -->
    <div class="cart-footer" style="margin-bottom: 50px;">
      <van-checkbox v-model="selectAll" class="select-all" @change="handleSelectAll">
        全选
      </van-checkbox>
      <div class="total-info">
        <span>合计: ¥{{ totalPrice.toFixed(2) }}</span>
        <van-button type="primary" :disabled="!hasSelected">结算({{ selectedCount }})</van-button>
      </div>
    </div>
    <!-- 底部导航栏 -->
    <van-tabbar v-model="active">
      <van-tabbar-item icon="home-o" @click="$router.push('/home')">首页</van-tabbar-item>
      <van-tabbar-item icon="search" @click="$router.push('/prolist')">分类</van-tabbar-item>
      <van-tabbar-item icon="friends-o" @click="$router.push('/cart')">购物车</van-tabbar-item>
      <van-tabbar-item icon="setting-o" @click="$router.push('/my')">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { getCartList } from '@/api/cart'; 
export default {
  name: 'ShoppingCart',
  data() {
    return {
      active: 2,
      // 商品数据，将flag改为checked保持与v-model一致
      cartItems: [
        {
          userid: 1,
          proname: "时尚休闲T恤",
          originprice: 99.99,
          img1: "https://picsum.photos/100/100?random=1",
          num: 1,
          checked: true
        },
        {
          userid: 2,
          proname: "夏季牛仔裤",
          originprice: 159.99,
          img1: "https://picsum.photos/100/100?random=2",
          num: 1,
          checked: true
        },
        {
          userid: 3,
          proname: "运动鞋",
          originprice: 299.99,
          img1: "https://picsum.photos/100/100?random=3",
          num: 1,
          checked: false
        }
      ],
      // 全选状态
      selectAll: false,
      // 合计金额
      totalPrice: 0
    };
  },
  computed: {
    // 是否显示空购物车状态
    showEmpty() {
      return this.cartItems.length === 0;
    },
    // 选中商品的数量
    selectedCount() {
      return this.cartItems.reduce((count, item) => {
        return item.checked ? count + item.num : count;
      }, 0);
    },
    // 是否有选中的商品
    hasSelected() {
      return this.selectedCount > 0;
    }
  },
  watch: {
    // 监听商品列表变化，更新全选状态和合计金额
    cartItems: {
      deep: true,
      handler() {
        this.updateSelectAllStatus();
        this.calculateTotal();
      }
    }
  },
  mounted() {
    // 初始化时计算一次总金额和全选状态
    this.calculateTotal();
    this.updateSelectAllStatus();

    // 注释掉不需要的后端接口调用
     const userid = localStorage.getItem('userid');
     console.log(userid);
     getCartList(userid).then(response => {
       console.log(response);
       this.cartItems = response.data.data;
     })
  },
  methods: {
    // 计算总金额
    calculateTotal() {
      this.totalPrice = this.cartItems.reduce((total, item) => {
        return item.checked ? total + (item.originprice * item.num) : total;
      }, 0);
    },

    // 更新全选状态
    updateSelectAllStatus() {
      if (this.cartItems.length === 0) {
        this.selectAll = false;
        return;
      }
      this.selectAll = this.cartItems.every(item => item.checked);
    },

    // 处理全选/取消全选
    handleSelectAll() {
      this.cartItems.forEach(item => {
        item.checked = this.selectAll;
      });
      this.calculateTotal();
    },

    // 删除商品
    deleteItem(index) {
      this.cartItems.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.cart-list {
  padding-bottom: 60px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin: 10px;
  background-color: #fff;
  border-radius: 8px;
}

.item-image {
  width: 80px;
  height: 80px;
  margin: 0 12px;
  border-radius: 4px;
  object-fit: cover;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 80px;
}

.item-name {
  font-size: 14px;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  color: #f4333c;
  font-weight: bold;
  margin: 0;
}

.van-icon {
  margin-left: 12px;
  font-size: 20px;
  cursor: pointer;
}

.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.select-all {
  font-size: 14px;
}

.total-info {
  display: flex;
  align-items: center;
}

.total-info span {
  margin-right: 16px;
  color: #f4333c;
  font-weight: bold;
}

.total-info .van-button {
  width: 120px;
}
</style>
